import {
  KEYUTIL,
  KJUR,
  RSAKey
} from "jsrsasign";

const DEFINE_JWKS_PATH = "/api/auth/.well-known/jwks.json"
const DEFINE_JWKS_KID = "f7aba4ee64d656c218f69b341f55d59b"

export function getJwks(value) {
  return new Promise((resolve, rejects) => {
    fetch(DEFINE_JWKS_PATH)
      .then((res) => res.json())
      .then((res) => {
        const kid = DEFINE_JWKS_KID;
        const data = res.keys.filter(
          (item) => item.kid === kid,
        )[0];
        const {
          kty,
          e,
          n
        } = data;
        const keyObj = KEYUTIL.getKey({
          kty,
          e,
          n,
        });
        const encrypt = KJUR.crypto.Cipher.encrypt(
          value,
          keyObj,
          "RSA",
        );
        resolve(encrypt);
      })
      .catch((error) => {
        rejects(error);
      });
  });
}
